/**
 * 
 */
package top.lcpsky.flashcards.web;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import top.lcpsky.flashcards.entity.CardsWithBLOBs;
import top.lcpsky.flashcards.service.CardsService;
import top.lcpsky.flashcards.util.ResponseResult;

/**
 * @ClassName: Cards
 * @author: lcp
 * @date: 2020年5月9日 下午9:40:48
 * 
 * @Copyright: 2020 www.ankept.com Inc. All rights reserved.
 */
@Api(tags = "卡片操作接口")
@Controller
@RequestMapping("cards")
public class CardsController {
	@Autowired
	private CardsService cardsSvc;

	@ApiOperation(value = "修改卡片",notes = "根据id修改卡片内容")
	@ApiImplicitParam(name="id",value = "卡片id",paramType = "query",required = true,dataType = "String")
	@GetMapping(value = "edit/{id}")
	public String toEditPage(HttpSession session, @PathVariable(name = "id") String id, Model model) {
		if (RouterController.getLoginStatus(session) == null) {
			return "redirect:/login";
		}
		CardsWithBLOBs card = cardsSvc.findCardById(Integer.valueOf(id.replace(",", "")));
		model.addAttribute("card", card);
		return "forward:/edit";
	}

	@PostMapping(value = "add")
	public String addCard(HttpSession session, CardsWithBLOBs card, Model model) {
		if (RouterController.getLoginStatus(session) == null) {
			return "redirect:login";
		}
		if (card.getType() != null) {
			cardsSvc.addCard(card);
		}
		return "redirect:/cards";
	}
	
	
	@RequestMapping("import")
	@ResponseBody
	public ResponseResult importMKSupportInfo(HttpServletRequest request, Model model) throws IOException {
		// 获取上传的文件
		MultipartHttpServletRequest multipart = (MultipartHttpServletRequest) request;
		MultipartFile file = multipart.getFile("uploadFile");
		String month = new Date().toString();
		InputStream in = file.getInputStream();
		ResponseResult status = cardsSvc.importInfo(in, file, month);
		in.close();
		return status;
	}
}
